package com.tencent.trtcsimpledemo.luis

import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import android.view.KeyEvent
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.microsoft.cognitiveservices.speech.*
import com.tencent.trtcsimpledemo.R
import kotlinx.android.synthetic.main.activity_luis_robot.*
import java.lang.ref.WeakReference
import java.sql.DriverManager.println
import java.util.concurrent.ExecutionException


class SugonAudioGuideActivity : AppCompatActivity() {

    private val speechSubscriptionKey = "32a88974600a4fc8bfcf078b4318852f"

    private val serviceRegion = "eastasia" // 东亚

    var mRecognizedContent = ""

    var mGotoPlace: String = ""


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_luis_robot)
        button.setOnClickListener {
            speechRecognize()
        }
    }


    private val mHandler = MyHandler(this)

    private class MyHandler(activity: SugonAudioGuideActivity) : Handler() {

        private val mActivity: WeakReference<SugonAudioGuideActivity> = WeakReference(activity)

        override fun handleMessage(msg: Message) {
            if (msg.what == 1) {
                refreshTxtContent(msg)
            } else if (msg.what == 2) {
                Toast.makeText(mActivity.get(), "语音未识别", Toast.LENGTH_SHORT).show()
            }

        }

        private fun refreshTxtContent(msg: Message) {
            val activity = mActivity.get()
            if (activity != null) {
                activity.txt_show_result.text = msg.obj.toString()

            }
        }
    }





    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {

        if (keyCode == 22 || keyCode == 21) { //22 往前滑动触控板， 21往后滑动触控板
            speechRecognize()
        }


        return super.onKeyUp(keyCode, event)
    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {

        Log.i("yjj", "SugonAudioGuideActivity onKeyDown >>>keyCode" + keyCode + ", action =" + event!!.action)
        if (keyCode == 66) {
            //todo sendStartMapToPhone()
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun speechRecognize() {
        Thread {

            try {
                recognitionWithLanguageAsync()
            } catch (e: InterruptedException) {
                e.printStackTrace()
            } catch (e: ExecutionException) {
                e.printStackTrace()
            }


        }.start()

    }


    // Speech recognition in the specified spoken language.
    @Throws(InterruptedException::class, ExecutionException::class)
    private fun recognitionWithLanguageAsync() {
        // Creates an instance of a speech config with specified
        // subscription key and service region. Replace with your own subscription key
        // and service region (e.g., "westus").
        val config = SpeechConfig.fromSubscription(speechSubscriptionKey, serviceRegion)

        // Creates a speech recognizer for the specified language, using microphone as audio input.

        val lang = "zh-CN"
        //String lang = "ru-RU"; //en-US   zh-CN

        config.speechRecognitionLanguage = lang

        val recognizer = SpeechRecognizer(config)

        run {
            // Starts recognizing.
            println("Say something in $lang ...")

            // Starts recognition. It returns when the first utterance has been recognized.
            val result = recognizer.recognizeOnceAsync().get()

            // Checks result.
            if (result.reason == ResultReason.RecognizedSpeech) {
                mRecognizedContent =  result.text
                println("RECOGNIZED: Text=" + result.text)

                val msg = mHandler.obtainMessage()
                msg.what = 1
                msg.obj = result.text
                mHandler.sendMessage(msg)
                if (mRecognizedContent != "" && mRecognizedContent != null) {
                    Log.i("yjj", "mRecognizedContent >>>> $mRecognizedContent")

                    getNumberWithRegex()

                }


            } else if (result.reason == ResultReason.NoMatch) {
                println("NOMATCH: Speech could not be recognized.")

                val msg = mHandler.obtainMessage()
                msg.what = 2
                mHandler.sendMessage(msg)

            } else if (result.reason == ResultReason.Canceled) {
                val cancellation = CancellationDetails.fromResult(result)
                println("CANCELED: Reason=" + cancellation.reason)

                if (cancellation.reason == CancellationReason.Error) {
                    println("CANCELED: ErrorCode=" + cancellation.errorCode)
                    println("CANCELED: ErrorDetails=" + cancellation.errorDetails)
                    println("CANCELED: Did you update the subscription info?")
                }
            }
            result.close()
        }

        config.close()
        recognizer.close()
    }

    private fun getNumberWithRegex() {
        // 这里的 \\D 等同于 [^0-9]
        val regEx = "\\D"
        //String regEx = "[^0-9]";
        // 把非0 - 9 的值替换为空字符串
        val s = mRecognizedContent.replace(regEx.toRegex(), "")
        Log.i("yjj", "number >>>> $s")

    }


}